package com.sanley.coronavirus.controller;

import com.github.pagehelper.PageInfo;
import com.sanley.coronavirus.bo.CheckOutBO;
import com.sanley.coronavirus.common.api.CommonResult;
import com.sanley.coronavirus.entity.CheckOut;
import com.sanley.coronavirus.entity.Cure;
import com.sanley.coronavirus.entity.User;
import com.sanley.coronavirus.service.CheckOutService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.security.Principal;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author: bonbon
 * @Date: 2021/4/15 15:48
 */
@Api("CheckOutController")
@Controller
@RequestMapping("/checkOut")
public class CheckOutController {
    @Autowired
    CheckOutService checkOutService;


    //打卡
    @ApiOperation("打卡提交")
    @PostMapping(value = "/add")
    @ResponseBody
    public CommonResult addCheckOut(@RequestBody CheckOutBO checkOutBO, Principal principal) {
        String username = principal.getName();
        checkOutService.add(username, checkOutBO);
        return CommonResult.success(null, "打卡成功");
    }

    @ApiOperation("获取个人打卡记录")
    @GetMapping("/getCheckOutById")
    @ResponseBody
    public CommonResult getCheckOutById(Principal principal) {
        String username = principal.getName();
        List<CheckOut> checkOuts = checkOutService.getCheckOutById(username);
        return CommonResult.success(checkOuts);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

    @ApiOperation("所有打卡记录")
    @GetMapping(value = "/list")
    @ResponseBody
    public CommonResult list(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "size", defaultValue = "25") int size) {
        List<CheckOut> checkOuts = checkOutService.findAll(page, size);
        PageInfo<User> pageInfo = new PageInfo(checkOuts);
        return CommonResult.success(pageInfo);
    }

    @ApiOperation("通过名称获取打卡记录")
    @GetMapping(value = "/listByCheckOutName")
    public String listByCureName(Model model, @RequestParam(name = "name") String name) {
        List<CheckOut> checkOut = checkOutService.findByName(name);
        PageInfo<Cure> pageInfo = new PageInfo(checkOut);
        model.addAttribute("pageInfo", pageInfo);
        return "checkOutList";
    }
}
